package com.wiseasy.ecrsdk2;

import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

//recyclerview 通用adapter
open class BaseAdapter<T>(private val mLayoutId: Int, val bind: (BaseViewHolder, Int, T) -> Unit) :
    RecyclerView.Adapter<BaseAdapter.BaseViewHolder>() {

    private var mContent: MutableList<T> = mutableListOf()
    private var itemClickListener: OnItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val view = createView(parent, viewType)
        return BaseViewHolder(view)
    }

    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        bind(holder, position, mContent[position])
        val t = mContent[position]
        if (itemClickListener != null) {
            holder.itemView.setOnClickListener {
                itemClickListener?.onItemClickListener(holder.itemView,position)
            }
        }
    }

    override fun getItemCount(): Int = mContent.size
    private fun createView(parent: ViewGroup, viewType: Int): View {
        return LayoutInflater.from(parent.context).inflate(mLayoutId, parent, false)
    }

    fun addItems(items: List<T>?, append: Boolean) {
        items?.let {
            if (!append) {
                mContent.clear()
            }
            mContent.addAll(it)
            notifyDataSetChanged()
        }
    }
    fun getData(): MutableList<T> {
        return mContent
    }

    class BaseViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        private val views: SparseArray<View> = SparseArray()
        operator fun <T : View> get(id: Int): T {
            var t = views.get(id)
            if (t == null) {
                t = itemView.findViewById(id)
                views.put(id, t)
            }
            return t as T
        }
    }


    interface OnItemClickListener {
        fun onItemClickListener(view: View, position: Int)

    }

    fun setItemClickListener(clickListener: OnItemClickListener) {
        itemClickListener = clickListener
    }

}